<?php

header('Content-Type: text/html; charset=utf-8');
error_reporting(0);
include_once 'DatabaseHelper.php';
require_once 'template.php';

//Start session
session_start();

$didLogin = FALSE;

if (!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) {
    $didLogin = FALSE;
} else {
    $didLogin = TRUE;
}

$header = new Page('template/header-tpl.php');
$mainpage = new Page('template/index-tpl.php');
$footer = new Page('template/footer-tpl.php');

//------------------------------BEGIN SETUP SLIDEBAR--------------------------------------
//slide bar, admin panel login or not login
$slidebar = new Page('template/slidebar-tpl.php');
if ($didLogin) {
    $adminPanel = new Page('template/admin-login.php');
    $slidebar->replace_tags(array(
        "admin_area" => $adminPanel->page
    ));
} else {
    $adminPanel = new Page('template/admin-nonlogin.php');
    $slidebar->replace_tags(array(
        "admin_area" => $adminPanel->page
    ));
}

//create category link
$category_query = "SELECT * FROM category";

DatabaseHelper::getInstance()->connect();
$result = DatabaseHelper::getInstance()->query($category_query);

$link_category = "";

while ($row = mysql_fetch_array($result)) {
    $id = $row['category_id'];
    $cateName = $row['category_name'];

    $num_post_query = "SELECT count(id)as num_post FROM post where category = $id and isdraft = 0";
    $num_post_result = DatabaseHelper::getInstance()->query($num_post_query);

    $num_post = 0;
    while ($num_post_row = mysql_fetch_array($num_post_result)) {
        $num_post = $num_post_row['num_post'];
    }

    $one_link = "<li><a href='index.php?c=$id'> $cateName ($num_post) </a> </li>";
    $link_category .= $one_link;
}

$slidebar->replace_tags(array(
    "category_area" => $link_category
));

//create recent post link
$recent_post_query = ("SELECT id, timestamp,title FROM post where isdraft = 0 order by timestamp DESC limit 5");
$recent_post_result = DatabaseHelper::getInstance()->query($recent_post_query);
$link_recent_post = "";

while ($row = mysql_fetch_array($recent_post_result)) {
    $idPost = $row['id'];
    $title = $row['title'];

    $timestamp = $row['timestamp'];
    $dateString = ' - ngày ' . date('d/m/Y', $timestamp);
    $one_link = "<li><a href=index.php?id=" . $idPost . ">" . $title . "</a>" . $dateString . "</li>";
    $link_recent_post .= $one_link;
}

$slidebar->replace_tags(array(
    "recent_post_area" => $link_recent_post
));

//create recent comment link
//syntax: Name + name of post + link to comment
$recent_comment_query = "SELECT c.entry,name,comment FROM comment as c,post as p
    where c.entry = p.id and p.isdraft = 0 order by c.timestamp DESC limit 5";
$recent_comment_result = DatabaseHelper::getInstance()->query($recent_comment_query);
$link_recent_comment = "";

while ($row = mysql_fetch_array($recent_comment_result)) {
    $idPost = $row['entry'];
    $name = $row['name'];
    $comment = $row['comment'];
    if (strlen($comment) > 100) {
        $comment = substr($comment, 0, 100);
        $comment .= " ...";
    }

    $title_post_query = "SELECT title FROM post where id = $idPost and isdraft = 0 limit 1";
    $title_post_result = DatabaseHelper::getInstance()->query($title_post_query);
    $title = "";

    while ($title_row = mysql_fetch_array($title_post_result)) {
        $title = $title_row['title'];
    }

    $one_link = "";
    if ($title != "") {
        $one_link = "<li> <b> $name</b> bình luận tại <i> <font color='brown'> $title </font> </i> : 
        <a href=index.php?id=" . $idPost . "#comment> $comment </a></li>";
    }
    $link_recent_comment .= $one_link;
}

$slidebar->replace_tags(array(
    "recent_comment_area" => $link_recent_comment
));



// create archieve link
$archive_query = ("SELECT FROM_UNIXTIME(timestamp, '%m') as get_month, 
                 FROM_UNIXTIME(timestamp, '%Y') AS get_year, 
                 COUNT(*) AS entries FROM post where isdraft = 0 GROUP BY get_month,get_year 
                 order by get_year DESC, get_month DESC");
$archive_result = DatabaseHelper::getInstance()->query($archive_query);

$link_archives = "";

while ($row = mysql_fetch_array($archive_result)) {
    $get_month = $row['get_month'];
    $get_year = $row['get_year'];
    $entries = $row['entries'];
    $one_link = "<li><a href=\"archives.php?month=" . $get_month . "&year=" . $get_year . "\">Tháng " . $get_month . " năm " . $get_year . "</a> (" . $entries . ")<li />";

    $link_archives .= $one_link;
}

$slidebar->replace_tags(array(
    "archive_area" => $link_archives
));

//------------------------------FINISH SETUP SLIDE BAR--------------------------------------
//------------------------------BEGIN SETUP PAGE CONTENT--------------------------------------

if (isset($_GET['id'])) {
    $postId = $_GET['id'];
    $query = "SELECT * FROM post where id = $postId and isdraft = 0";

    $result = DatabaseHelper::getInstance()->query($query);
    $content = "";

    $numRow = DatabaseHelper::getInstance()->numberResultRow($result);

    if ($numRow == 0) {
        $content = "<div style = 'color:red; margin-left:40px;margin-top:40px; font-size:20px'>Không có bài viết này </div>";
        $mainpage->replace_tags(array(
            "comment_separate" => "",
            "comment" => ""
        ));
    } else {
        while ($row = mysql_fetch_array($result)) {
            $id = $row['id'];
            $cate_id = $row['category'];
            $title = stripslashes($row['title']);
            $entry = stripslashes($row['entry']);
            $summary = strip_tags($row['entry']);
            $closeComment = $row['hidecomment'];



            $timestamp = $row['timestamp'];
            $dateString = "Đăng vào lúc " . date('H:i:s d-m-Y', $timestamp);

            if (strlen($entry) > 500)
                $moreLink = "<a style='color:blue;font-style:italic' href=\"index.php?id=" . $id . "\">Xem chi tiết</a>";

            $summary = add3dots($summary, " ...", 500);
            $readLink = "<a href=\"index.php?id=" . $id . "\">$title</a>";

            $page = new Page('template/post-tlp.php');

            //include admin_panel
            $admin_panel = "";

            if ($didLogin) {
                $form_admin = new Page('template/post-admin-tpl.php');

                if ($closeComment == 0) {
                    $form_admin->replace_tags(array(
                        "confirm_message_comment" => "Ko cho phép bình luận bài viết này?",
                        "close_or_open_comment" => "close_comment",
                        "comment_action" => "Đóng bluận",
                        "postid" => $id
                    ));
                } else {
                    $form_admin->replace_tags(array(
                        "confirm_message_comment" => "Cho phép bình luận ở bài viết này?",
                        "close_or_open_comment" => "open_comment",
                        "comment_action" => "Mở bluận",
                        "postid" => $id
                    ));
                }

                $admin_panel = $form_admin->page;
            }

            $page->replace_tags(array(
                "title" => $readLink,
                "content" => $entry,
                "date" => $dateString,
                "comment" => "",
                "more" => "",
                "admin_panel" => $admin_panel
            ));
            $content .= "$page->page";
        }

        //show all comment
        $id = $_GET['id'];
        $commentQuery = "SELECT * FROM comment where entry ='$id' order by timestamp DESC";

        $commentResult = DatabaseHelper::getInstance()->query($commentQuery);
        $numComment = DatabaseHelper::getInstance()->numberResultRow($commentResult);

        if ($numComment == 0) {
            $mainpage->replace_tags(array(
                "comment_separate" => "<p style = 'margin-left:30px; color:bluevilet;font-size:20px'>Chưa có bình luận nào</p>",
                "comment" => ""
            ));
        } else {
            $allComment = "";
            while ($row = mysql_fetch_array($commentResult, MYSQL_ASSOC)) {
                $name = $row['name'];
                $commentText = $row['comment'];
                $dateString = "Bình luận vào " . date('H:i:s d-m-Y', $row['timestamp']);
                $timestamp = $row['timestamp'];
                $commentId = $row['id'];

                if ($didLogin)
                    $adminitems = "<form class=\"inline\" action=\"comment.php\" method=\"post\">
							<input class=\"blink\" type=\"button\" onclick=\"self.location='?id=$id&e=$commentId#form_comment'\" value=\"Edit\">
							<input class=\"blink\" type=\"submit\" onclick=\"return confirm('Bạn có muốn xóa comment này?')\" value=\"Delete\" name=\"delete\">
							<input type=\"hidden\" value=\"$commentId\" name=\"commentid\" id=\"commentid\">
							<input type=\"hidden\" value=\"$id\" name=\"entry\" id=\"entry\">
							</form>";
                else
                    $adminitems = "";

                $commentItem = new Page('template/comment-item.php');
                $commentItem->replace_tags(array(
                    "comment_name" => $name,
                    "comment_text" => $commentText,
                    "comment_date" => $dateString,
                    "admin_items" => $adminitems,
                ));

                $allComment .= $commentItem->page;
            }

            $comment_separate = new Page('template/comment-title.php');
            $mainpage->replace_tags(array(
                "comment_separate" => $comment_separate->page,
                "comment" => $allComment
            ));
        }

        $commentForm = "<div style='color:red; font-size:20px; margin-left:30px; margin-top:40px'>Chức năng bình luận đã bị đóng</div>";

        if ($closeComment == 0 || (isset($_GET['e']) && $didLogin)) {
            $commentPage = new Page('template/comment-form.php');
            //------------------------------BEGIN EDIT CONTENT------------------------------------------
            if (isset($_GET['e']) && $didLogin) {
                $id = $_GET['id'];
                $commentId = $_GET['e'];
                $commentQuery = "SELECT * FROM comment where entry ='$id' and id = '$commentId'";

                $commentResult = DatabaseHelper::getInstance()->query($commentQuery);
                $numComment = DatabaseHelper::getInstance()->numberResultRow($commentResult);

                if ($commentResult) {
                    $row = mysql_fetch_array($commentResult, MYSQL_ASSOC);
                    $commentPage->replace_tags(array(
                        "post_id" => $_GET['id'],
                        "hoten" => $row['name'],
                        "email" => $row['email'],
                        "comment" => $row['comment'],
                        "commentId" => $commentId,
                        "action" => "Lưu sửa"
                    ));
                }
            }//------------------------------FINISH EDIT CONTENT------------------------------------------
            else {
                $commentPage->replace_tags(array(
                    "post_id" => $_GET['id'],
                    "hoten" => "",
                    "email" => "",
                    "comment" => "",
                    "commentId" => "-1",
                    "action" => "Bình luận"
                ));
            }

            $commentForm = $commentPage->page;
        }
    }


    $mainpage->replace_tags(array(
        "header" => $header->page,
        "main_content" => $content,
        "slidebar" => $slidebar->page,
        "footer" => $footer->page,
        "comment_form" => $commentForm,
        "category_name" => "",
        "page_nav" => ""
    ));
} else {
    // search
    require_once 'unsignedchar.php';

    if (isset($_GET['keySearch'])) {
        $keySearch = $_GET['keySearch'];
        $query = "SELECT * FROM post order by timestamp DESC";
        $result = DatabaseHelper::getInstance()->query($query);
        $num = DatabaseHelper::getInstance()->numberResultRow($result);
        $content = "";

        $num_found = 0;

        while ($row = mysql_fetch_array($result)) {
            $id = $row['id'];
            $title = $row['title'];
            $entry = $row['entry'];

            $tmpTitle = strtolower(unsignedtext($title));
            $tmpEntry = strtolower(unsignedtext($entry));
            $tmpKeySearch = trim(strtolower(unsignedtext($keySearch)));

            $found = FALSE;


            // If keysearch not appear in title of post and keysearch not appear in entry of post

            if ((strpos($tmpTitle, $tmpKeySearch) !== false) || (strpos($tmpEntry, $tmpKeySearch) !== false)) {
                $found = true;
                $num_found += 1;
            } else {
                $cQuery = "SELECT * FROM comment where entry ='$id'";
                $cResult = DatabaseHelper::getInstance()->query($cQuery);

                while ($crow = mysql_fetch_array($cResult)) {
                    $name = $crow['name'];
                    $email = $crow['email'];
                    $comment = $crow['comment'];

                    $name = strtolower(unsignedtext($name));
                    $email = strtolower(unsignedtext($email));
                    $comment = strtolower(unsignedtext($comment));

                    if ((strpos($name, $tmpKeySearch) !== false) || (strpos($email, $tmpKeySearch) !== false) || (strpos($comment, $tmpKeySearch) !== false)) {
                        $found = true;
                        $num_found += 1;
                        break;
                        ;
                    }
                }
            }

            if ($found) {

                $entry = strip_tags($entry);
                if (strlen($entry) > 400)
                    $moreLink = "<a style='color:blue;font-style:italic' href=\"index.php?id=" . $id . "\">Xem chi tiết</a>";

                $entry = add3dots($entry, " ...", 400);
                $readLink = "<a href=\"index.php?id=" . $id . "\">$title</a>";
                $timestamp = $row['timestamp'];
                $dateString = 'Ðăng vào ngày ' . date('H:i:s d-m-Y', $timestamp);

                $page = new Page('template/post-tlp.php');
                $page->replace_tags(array(
                    "title" => $readLink,
                    "content" => $entry,
                    "date" => $dateString,
                    "comment" => "",
                    "more" => $moreLink,
                    "admin_panel" => ""
                ));
                $content .= "$page->page";
            }
        }


        $mainpage->replace_tags(array(
            "header" => $header->page,
            "main_content" => $content,
            "slidebar" => $slidebar->page,
            "footer" => $footer->page,
            "comment_form" => "",
            "category_name" => "Tìm thấy $num_found kết quả",
            "comment_separate" => "",
            "comment" => "",
            "page_nav" => ""
        ));
    } else {
        $page_select = 1;

        if (isset($_GET['page'])) {
            $page_select = $_GET['page'];
        }

        if (isset($_GET['c'])) {
            $cateID = $_GET['c'];
            $query = "SELECT * FROM post where category = $cateID and isdraft = 0 order by timestamp DESC";
        } else {
            $query = "SELECT * FROM post where isdraft = 0 order by timestamp DESC";
        }

        $result = DatabaseHelper::getInstance()->query($query);
        $num = DatabaseHelper::getInstance()->numberResultRow($result);
        $numpage = 1;
        $numpage = intval($num / MAX_POST);
        if ($numpage * MAX_POST < $num) {
            $numpage += 1;
        }

        $i = 0;
        $content = "";

        if ($num == 0) {
            $content = "<p style = 'margin-left:30px; color:red;font-size:15px'>Không có bài viết nào</p>";
        }

        $offsetX = ($page_select - 1) * MAX_POST;
        $offsetY = MAX_POST * $page_select;

        for ($i = 0; $i < $num; $i++) {
            if (($i >= $offsetX) && ($i < $offsetY)) {
                $id = mysql_result($result, $i, "id");
                $title = mysql_result($result, $i, "title");
                $entry = strip_tags(mysql_result($result, $i, "entry"));
                $closeComment = mysql_result($result, $i, "hidecomment");

                $summary = add3dots($entry, " ...", 500);

                $readLink = "<a href=\"index.php?id=" . $id . "\">$title</a>";
                $timestamp = mysql_result($result, $i, "timestamp");
                $dateString = 'Ðăng vào ngày ' . date('H:i:s d-m-Y', $timestamp);

                if (strlen($entry) > 500)
                    $moreLink = "<a style='color:blue;font-style:italic' href=\"index.php?id=" . $id . "\">Xem chi tiết</a>";
                else {
                    $moreLink = "";
                }

                $page = new Page('template/post-tlp.php');
                $commentQuery = "SELECT id FROM comment where entry ='$id'";
                $commentResult = DatabaseHelper::getInstance()->query($commentQuery);
                $numComment = DatabaseHelper::getInstance()->numberResultRow($commentResult);
                $commemtLink = "<a href=index.php?id=" . $id . "#comment> Có " . $numComment . " bình luận</a>";

                if ($didLogin) {
                    $form_admin = new Page('template/post-admin-tpl.php');

                    if ($closeComment == 0) {
                        $form_admin->replace_tags(array(
                            "confirm_message_comment" => "Ko cho phép bình luận bài viết này?",
                            "close_or_open_comment" => "close_comment",
                            "comment_action" => "Đóng bluận",
                            "postid" => $id
                        ));
                    } else {
                        $form_admin->replace_tags(array(
                            "confirm_message_comment" => "Cho phép bình luận ở bài viết này?",
                            "close_or_open_comment" => "open_comment",
                            "comment_action" => "Mở bluận",
                            "postid" => $id
                        ));
                    }

                    $admin_panel = $form_admin->page;
                }

                $page->replace_tags(array(
                    "title" => $readLink,
                    "content" => $summary,
                    "date" => $dateString,
                    "comment" => $commemtLink,
                    "more" => $moreLink,
                    "admin_panel" => $admin_panel
                ));

                $content .= "$page->page";
            }
        }

        //get Title of Main Content (All post or post in category)
        $cate_name = "Tất cả bài viết";
        if (isset($_GET['c'])) {
            //set name of category here
            $cateID = $_GET['c'];
            $cate_query = "SELECT category_name FROM category where category_id = $cateID limit 1;";


            $cate_result = DatabaseHelper::getInstance()->query($cate_query);
            while ($row = mysql_fetch_array($cate_result)) {
                $cate_name = $row['category_name'];
            }
        }

        //build navigate link
        $page_nav = "";

        if ($numpage > 1) {
            $page_nav .= "Trang";
            for ($i = 1; $i <= $numpage; $i++) {
                if ($cateID != "")
                    $category = "&c=$cateID";

                if ($i == $page_select) {
                    $page_nav .= " <a class=\"currentpage\" href=\"index.php?page=$i$category\">$i</a> ";
                } else {
                    $page_nav .= " <a class=\"pagelink\" href=\"index.php?page=$i$category\">$i</a> ";
                }
                if ($i != $numpage)
                    $page_nav .= "|";
            }
        }



        $mainpage->replace_tags(array(
            "header" => $header->page,
            "main_content" => $content,
            "slidebar" => $slidebar->page,
            "footer" => $footer->page,
            "comment_form" => "",
            "category_name" => $cate_name,
            "comment_separate" => "",
            "comment" => "",
            "page_nav" => $page_nav
        ));
    }
}
//------------------------------FINISH SETUP PAGE CONTENT--------------------------------------
DatabaseHelper::getInstance()->close();
$mainpage->output();

function add3dots($string, $repl, $limit) {
    if (strlen($string) > $limit) {
        return substr($string, 0, $limit) . $repl;
    } else {
        return $string;
    }
}

?>
